const BASE_URL = 'http://localhost:3000' // 设置基础URL

// 请求拦截器
const requestInterceptor = (config) => {
	// 获取token
	const token = uni.getStorageSync('token')
	if (token) {
		config.header = {
			...config.header,
			'Authorization': `Bearer ${token}`
		}
	}
	return config
}

// 响应拦截器
const responseInterceptor = (response) => {
	const { statusCode, data } = response
	
	if (statusCode >= 200 && statusCode < 300) {
		// 请求成功
		if (data.code === 200) {
			return data.data
		} else {
			// 业务错误
			uni.showToast({
				title: data.message || '请求失败',
				icon: 'none'
			})
			return Promise.reject(data)
		}
	} else if (statusCode === 401) {
		// token过期或未登录
		uni.showToast({
			title: '请重新登录',
			icon: 'none'
		})
		// 清除token
		uni.removeStorageSync('token')
		// 跳转到登录页
		setTimeout(() => {
			uni.reLaunch({
				url: '/pages/login/index'
			})
		}, 1500)
		return Promise.reject(response)
	} else {
		// 其他错误
		uni.showToast({
			title: '网络错误',
			icon: 'none'
		})
		return Promise.reject(response)
	}
}

// 封装请求方法
const request = (options) => {
	return new Promise((resolve, reject) => {
		const config = requestInterceptor({
			url: BASE_URL + options.url,
			method: options.method || 'GET',
			data: options.data,
			header: options.header || {}
		})
		
		uni.request({
			...config,
			success: (res) => {
				try {
					const result = responseInterceptor(res)
					resolve(result)
				} catch (error) {
					reject(error)
				}
			},
			fail: (err) => {
				uni.showToast({
					title: '网络请求失败',
					icon: 'none'
				})
				reject(err)
			}
		})
	})
}

// 封装GET请求
export const get = (url, params = {}) => {
	return request({
		url,
		method: 'GET',
		data: params
	})
}

// 封装POST请求
export const post = (url, data = {}) => {
	return request({
		url,
		method: 'POST',
		data
	})
}

// 导出请求方法
export default {
	get,
	post
} 